package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryById(Long id) {
        //1、缓存穿透
//        Shop shop = queryWithPassThrough(id);
        //2、缓存击穿 基于逻辑时过期
//        Shop shop = queryWithLogicalExpire(id);
//        3、采用工具类进行调用缓存穿透
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //4、
        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        //7、返回
        return Result.ok(shop);
    }


    @Override
    @Transactional
    public Result updateByShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺Id不能为空");
        }
        //1、更新数据库
        updateById(shop);
        //2、删除缓存，当使用的时候再进行加载
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }


    public final static ExecutorService CACHE_REBUILD_EXECTOR = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期时间处理缓存击穿问题
     *
     * @param id
     * @return
     */
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1、通过id从redis  查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断缓存是否存在
        if (StrUtil.isBlank(shopJson)) {
            //如果不存在直接返回错误
            return null;
        }

        //5、数据存在，则进行发序列化操作
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        //获取逻辑时间
        LocalDateTime expireTime = redisData.getExpireTime();
        //6、获取逻辑时间是否过去
        if (expireTime.isAfter(LocalDateTime.now())) {
            //未过期
            return shop;
        }
        //7、过期 缓存重建
        //7.1获取互斥锁
        boolean tryLock = tryLock(LOCK_SHOP_KEY + id);
        if (tryLock) {
            //当我持有这把锁，需要线程缓存重建
            try {
                CACHE_REBUILD_EXECTOR.submit(() -> {
                    saveShop2Redis(id, 20L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unlock(LOCK_SHOP_KEY + id);
            }
        }
        return shop;
    }

    /**
     * 热点数据 缓存击穿 基于互斥锁
     *
     * @param id
     * @return
     */
    public Shop queryWithMutex(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1、通过id从redis  查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2、判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3、存在直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 数据为空字符串直接进行返回错误
        if (shopJson != null) {
            return null;
        }

        //4、实现缓存重建
        //4.1获取互斥锁
        //4、2判断是否获取成功
        Shop shop = null;
        try {
            boolean tryLock = tryLock(LOCK_SHOP_KEY + id);
            //4、3 失败休眠一会，重新尝试获取
            if (!tryLock) {
                Thread.sleep(50);
                //注意这块需要重置 等待循环，采用递归的方式，如果没有持有锁  继续调用
                return queryWithMutex(id);
            }
            //4、不存在去数据库查询
            shop = getById(id);
//            Thread.sleep(200);
            //5、数据不能存在 直接返回错误
            if (shop == null) {
                //5.1 如果从数据库查询不存在，将空数据打入到内存，防止缓存穿透，只对数据库查询一次
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //6、数据存在存储到redis,存入缓存，需要设置剔除时间，和写入数据的主动更新缓存进行配合使用
            stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            //7、返回
            //8. 释放互斥锁
            unlock(LOCK_SHOP_KEY + id);
        }

        return shop;
    }

    /**
     * 缓存穿透 基于设置valuse为为空
     *
     * @param id
     * @return
     */
    public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;
        //1、通过id从redis  查询数据
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
        //2、判断缓存是否存在
        if (StrUtil.isNotBlank(shopJson)) {
            //3、存在直接返回
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }
        // 数据为空字符串直接进行返回错误
        if (shopJson != null) {
            return null;
        }
        //4、不存在去数据库查询
        Shop shop = getById(id);
        //5、数据不能存在 直接返回错误
        if (shop == null) {
            //5.1 如果从数据库查询不存在，将空数据打入到内存，防止缓存穿透，只对数据库查询一次
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }

        //6、数据存在存储到redis,存入缓存，需要设置剔除时间，和写入数据的主动更新缓存进行配合使用
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7、返回
        return shop;
    }

    /**
     * 数据重建,
     */
    public void saveShop2Redis(Long id, Long expiryTimeSeconds) {
        //1、获取shop数据
        Shop shop = getById(id);
        //  测试数据延迟200毫秒
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //2、封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expiryTimeSeconds));
        //3、写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    /***
     *@Description 创建互斥锁
     *@param key
     */
    public boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(aBoolean);
    }

    /**
     * 删除互斥锁
     *
     * @param key
     */
    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

}
